package com.ustcinfo.study.hive.r5.hesong;

import java.sql.*;

/**
 * Describe:  使用JDBC的方式连接  HIVE   进行查询
 * Author: hesong
 */

public class MyHiveJdbc {
        // hive连接地址
        private static String url = "jdbc:hive2://node1:10000/default";

        //hive用户名    数据库用户名
        private static String userName = "root";

        // hive密码     数据库密码
        private static String passwd = "123456";

        // hive 驱动
        private static String driver = "org.apache.hive.jdbc.HiveDriver";

        private static Connection connection = null;
        private static Statement statement = null;
        private static ResultSet resultSet = null;

        // 查询tables sql
        private static String showTableSql = "show tables";

        // 统计出统一域名的访问次数sql
        private static String countSql = "select domain_name,count(*) from dns_hesong group by domain_name";

        public static void main(String[] args) throws SQLException {

            //  加载hive驱动
            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                System.out.println("驱动加载失败");
                e.printStackTrace();
            }

            try {
                // 连接hive
                connection = DriverManager.getConnection(url, userName, passwd);
                if (connection != null) {
                    System.out.println("hive 连接成功");
                } else {
                    System.out.println("hive 连接失败");
                }
                statement = connection.createStatement();
                //执行查询语句，获得结果
                resultSet = statement.executeQuery(countSql);
                while (resultSet.next()) {
                    System.out.println(resultSet.getString("domain_name") + "\t" + resultSet.getInt(2));
                }

            } catch (SQLException e) {
                e.printStackTrace();
                System.exit(1);
            } finally {
                if (statement != null) {
                    statement.close();
                }
                if(connection != null) {
                    connection.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }


        }

    }

